package com.limox.bishe.activity;

import java.io.IOException;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;

import com.limox.bishe.R;
import com.limox.bishe.app.APP;
import com.limox.bishe.db.DataBaseManager;
import com.limox.bishe.http.HttpUtil;
import com.limox.bishe.http.StringUtil;
import com.limox.bishe.util.Util;

import android.R.string;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.ActionBar;
import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences.Editor;
import android.database.sqlite.SQLiteDatabase;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.SearchView;
import android.widget.Toast;

public class LoginActivity extends Activity {
	DefaultHttpClient mHttpClient = new DefaultHttpClient();
	private int SchoolNum = 0; // 学校代码，吉林大学珠海学院->0
	String temp = "";
	String __VIEWSTATE = "";
	EditText edit_username;
	EditText edit_userkey;
	String xh;
	String xm;
	private SQLiteDatabase SQLdb;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);

		final ActionBar actionBar = getActionBar();

		edit_username = (EditText) findViewById(R.id.edit_login_username);
		edit_userkey = (EditText) findViewById(R.id.edit_login_userkey);

		// 判断是否已经登陆，如果已登陆直接跳到下一个界面
		if (!Util.ReadSharedPerference(LoginActivity.this, "jwinfo",
				"user_name").equals("null")) {
			Intent goIntent = new Intent();
			goIntent.setClass(LoginActivity.this, kbActivity.class);
			goIntent.putExtra("isNewUser", false);
			startActivity(goIntent);
			finish();
		}

		// 初始化客户端
		initHttpClient();

		/*
		 * 登陆按钮监听
		 */
		findViewById(R.id.but_login).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (edit_username.getText().toString().equals("")
						| edit_userkey.getText().toString().equals("")) {
					// have no edit
					Toast.makeText(LoginActivity.this, "我掐指一算，你有东西没写完", 1)
							.show();
				} else {
					// get the __VIEWSTATE
					// 此处先获取页面，读取到__VIEWSTATE值为post做准备
					GetVIEVSTATE();

				}

			}
		});

	}

	/**
	 * 登陆请求
	 */
	protected void POSTLogin() {
		// TODO Auto-generated method stub

		new AsyncTask<Void, Void, Void>() {
			protected Void doInBackground(Void... params) {
				// 后台任务
				temp = HttpUtil.PostUrl(__VIEWSTATE, edit_username.getText()
						.toString(), edit_userkey.getText().toString(), APP
						.getUrl(SchoolNum), mHttpClient);

				return null;
			}

			@Override
			protected void onPostExecute(Void result) {
				// 界面刷新操作
				if (temp == null | temp == "") {
					Toast.makeText(LoginActivity.this, "登陆失败，请检查网络", 1).show();
				} else {
					System.out.println("temp:" + temp);
					StringTokenizer tokenizer = new StringTokenizer(temp);

					while (tokenizer.hasMoreTokens()) {
						String valueToken = tokenizer.nextToken();
						if (StringUtil.isValue(valueToken, "defer")) {
							Toast.makeText(LoginActivity.this, "用户验证失败", 1)
									.show();
						}
						if (StringUtil.isValue(valueToken, " <title>ERROR")) {
							Toast.makeText(LoginActivity.this, "系统正忙，请稍后再试", 1)
									.show();
						}

						// 获取学名
						if (StringUtil.isValue(valueToken, "id=\"xhxm")) {
							System.out.println(valueToken);
							xm = StringUtil.getValue(valueToken, "id=\"xhxm>",
									"</span>", 11);// value
							System.out.println("xm:" + xm);

							// 本地保存学号和密码
							Util.SharedPerferencesCreat(LoginActivity.this,
									"jwinfo", "user_name", xm);

						}
					} 

					// 获取学号
					xh = edit_username.getText().toString();

					Util.SharedPerferencesCreat(LoginActivity.this, "jwinfo",
							"user_xh", xh);

					// 保存school_id（学校代码+学号）
					Util.SharedPerferencesCreat(LoginActivity.this, "jwinfo",
							"school_id", APP.SchoolIdHead[SchoolNum] + xh);

					Toast.makeText(LoginActivity.this, "欢迎" + xm + "同学", 0)
							.show();
					// 获取课表信息
					GetKbInfo();

				}

			}

		}.execute((Void) null);

	}

	/**
	 * 获取课表信息
	 */
	protected void GetKbInfo() {
		// TODO Auto-generated method stub
		new Thread(new Runnable() {
			public void run() {
				try {
					temp = HttpUtil.getUrl("http://" + APP.getUrl(SchoolNum)
							+ "/xskbcx.aspx?xh=" + xh + "&xm=" + xm
							+ "&gnmkdm=N121603", mHttpClient,
							"http://" + APP.getUrl(SchoolNum)
									+ "/xs_main.aspx?xh=" + xh);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				temp = temp.replaceAll("</td>", "</td>\n");// 转化换行

				Pattern p = Pattern.compile("(?<=>).*(?=</td>)");
				Matcher m = p.matcher(temp);
				String[] ss = null;
				String kbInfoAll = "";
				ss = new String[400];
				int i = 0;

				while (m.find() && (!m.group().toString().equals("编号"))) {
					if (!(m.group().toString().equals("&nbsp;"))
							&& !(m.group().toString().equals(""))
							&& !(m.group().toString().equals("早晨"))
							&& !(m.group().toString().equals("上午"))
							&& !(m.group().toString().equals("下午"))
							&& !(m.group().toString().equals("晚上"))
							&& !(m.group().toString().substring(0, 1)
									.equals("星"))
							&& !(m.group().toString().equals("时间"))
							&& !(m.group().toString().substring(0, 1)
									.equals("第"))) {
						ss[i] = m.group().toString();

						kbInfoAll = kbInfoAll + ss[i] + "\n";
						i++;
					}
				}

				// 保存课表在本地
				Util.SharedPerferencesCreat(LoginActivity.this, "kb_info",
						"kb_all", kbInfoAll);
				// 分析课表信息并保存在数据库
				SaveKbinfo2Db();

				// 跳转到课表界面
				Intent goIntent = new Intent();
				goIntent.setClass(LoginActivity.this, kbActivity.class);
				goIntent.putExtra("isNewUser", true);

				startActivity(goIntent);
				finish();

			}
		}).start();

	}

	/**
	 * 分析课表信息，并保存在数据库
	 */
	protected void SaveKbinfo2Db() {
		// TODO Auto-generated method stub
		// 数据库如果不存在则建数据库
		DataBaseManager.CreateDatabase(LoginActivity.this, "kb", null);
		SQLdb = DataBaseManager.OpenDb(LoginActivity.this, "kb", null, 3);
		// 创建数据库
		DataBaseManager.CreateTable_Kb(SQLdb);

		// 分析课表信息，并保存
		String[] kbstr = Util.ReadSharedPerference(LoginActivity.this,
				"kb_info", "kb_all").split("<br>");
		String NewArrayKbStr[] = new String[400];
		int k = 0;

		for (int i = 0; i < kbstr.length; i++) {
			if (kbstr[i].indexOf("\n") == -1) {
				// 没有检索到"\n"
				if (kbstr[i] != "" && kbstr[i] != null && !kbstr[i].equals("")) {
					// 将节数和时间分开
					if (kbstr[i].indexOf("{") != -1) {
						String[] jieStr = kbstr[i].split("\\{");
						NewArrayKbStr[k] = jieStr[0];
						NewArrayKbStr[k + 1] = jieStr[1].replace("}", "");
						k = k + 2;
					} else {
						NewArrayKbStr[k] = kbstr[i];
						k++;
					}
				}

			} else {
				// 包含"\n"，该字符串包含两个信息，需分开处理
				String[] twoInfo = kbstr[i].split("\n");
				if (twoInfo.length == 2) {
					NewArrayKbStr[k] = twoInfo[0];
					NewArrayKbStr[k + 1] = twoInfo[1];
					k = k + 2;
				}
				// 最后一行的情况
				if (twoInfo.length == 1) {
					NewArrayKbStr[k] = twoInfo[0];
					k++;
				}
			}

		}

		// 保存数据库
		ArrayList<HashMap<String, String>> arraylist = new ArrayList<HashMap<String, String>>();

		int i = 0;
		HashMap<String, String> map = new HashMap<String, String>();

		while (NewArrayKbStr[i] != null) {
			System.out.println("课表：" + NewArrayKbStr[i]);

			switch (i % 5) {
			case 0:
				map.put("cour_name", NewArrayKbStr[i]);
				break;
			case 1:
				map.put("time", NewArrayKbStr[i]);
				break;
			case 2:
				map.put("week", NewArrayKbStr[i]);
				break;
			case 3:
				map.put("teacher", NewArrayKbStr[i]);
				break;
			case 4:
				map.put("classroom", NewArrayKbStr[i]);
				break;
			default:
				break;
			}

			if (i % 5 == 4) {
				arraylist.add(map);
				map = new HashMap<String, String>();
			}

			i++;
		}

		// 保存到数据库
		/**
		 * 插入一条课表信息
		 * 
		 * @param db
		 * @param school_id
		 * @param cour_name
		 * @param teacher
		 * @param classroom
		 * @param week
		 * @param time
		 */

		for (int l = 0; l < arraylist.size(); l++) {
			DataBaseManager.InsertTb_xq(SQLdb, Util.ReadSharedPerference(
					LoginActivity.this, "jwinfo", "school_id"), arraylist
					.get(l).get("cour_name"), arraylist.get(l).get("teacher"),
					arraylist.get(l).get("classroom"),
					arraylist.get(l).get("week"), arraylist.get(l).get("time"));

		}

	}

	/**
	 * GET 请求网站并获取需要的_VIEVSTATE 值 然后 post请求登陆
	 * 
	 */
	protected void GetVIEVSTATE() {
		// TODO Auto-generated method stub

		// 第一次登陆获取__VIEWSTATE
		new AsyncTask<Void, Void, Void>() {
			protected Void doInBackground(Void... params) {
				// 后台任务
				try {
					temp = HttpUtil.getUrl("http://" + APP.getUrl(SchoolNum),
							mHttpClient, "");
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				return null;
			}

			@Override
			protected void onPostExecute(Void result) {
				// 界面刷新操作
				if (temp == "") {
					Toast.makeText(LoginActivity.this, "登陆失败，请检查网络", 1).show();
				} else {
					// 创建分分词器
					StringTokenizer tokenizer = new StringTokenizer(temp);

					while (tokenizer.hasMoreTokens()) {
						String valueToken = tokenizer.nextToken();
						if (StringUtil.isValue(valueToken, "value")) {
							if (StringUtil.getValue(valueToken, "value", "\"",
									7).length() == 48) {
								__VIEWSTATE = StringUtil.getValue(valueToken,
										"value", "\"", 7);// value
								break;
							}
						}
					}
				}

				// 登陆
				POSTLogin();

			}

		}.execute((Void) null);

	}

	/**
	 * 初始化httpclient 的设置
	 */
	private void initHttpClient() {
		// TODO Auto-generated method stub
		// 请求超时
		mHttpClient.getParams().setParameter(
				CoreConnectionPNames.CONNECTION_TIMEOUT, 10000); // determines
																	// the
																	// timeout
																	// until a
																	// connect
																	// is
																	// established

		// 读取超时
		mHttpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,
				10000);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.

		getMenuInflater().inflate(R.menu.main, menu);
		return super.onCreateOptionsMenu(menu);

	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		switch (item.getItemId()) {
		case R.id.action_settings:
			Toast.makeText(LoginActivity.this, "设置", 1).show();
			break;

		default:
			break;
		}

		return super.onOptionsItemSelected(item);
	}

}
